package site.edody.dframe.plugin;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 通用动态代码执行管理器
 * 整合编译、实例化和方法调用，提供统一的API
 */
public class DynamicCodeExecutor {
    private final CodeBasedDependencyManager dependencyManager;
    private final DynamicJavaCompiler compiler;
    private final DynamicMethodInvoker invoker;
    private final ClassLoaderCompatibilityHelper compatibilityHelper; // 新增


    private static final Logger log = LoggerFactory.getLogger(DynamicCodeExecutor.class);

    public DynamicCodeExecutor(CodeBasedDependencyManager dependencyManager,DynamicJavaCompiler dynamicJavaCompiler,DynamicMethodInvoker dynamicMethodInvoker,ClassLoaderCompatibilityHelper compatibilityHelper) {
        this.dependencyManager = dependencyManager;
        this.compiler = dynamicJavaCompiler;
        this.invoker = dynamicMethodInvoker;
        this.compatibilityHelper = compatibilityHelper;
    }




    /**
     * 编译并执行Java源代码
     */
    public Object executeSourceCode(String className, String sourceCode,
                                    String methodName, ArrayList<Object> params) throws Exception {
        // 编译源代码
        Class<?> clazz = compiler.compileSource(className, sourceCode);
        log.info("源代码编译成功: {}", className);

        // 实例化类
        Object instance = invoker.instantiateClass(className);
        log.info("类实例化成功: {}", className);

        // 调用方法
        return invoker.invokeInstanceMethod(instance, methodName, params);
    }

    /**
     * 生成接口实现并执行方法
     */
    public Object executeInterfaceImplementation(String className, String interfaceName,
                                                 Map<String, Object> methodImplementations,
                                                 String methodName, ArrayList<Object> params) throws Exception {
        // 生成接口实现类
        Class<?> implClass = compiler.generateInterfaceImplementation(className, interfaceName, methodImplementations);
        log.info("接口实现类生成成功: {} -> {}", className, interfaceName);

        // 实例化类
        Object instance = invoker.instantiateClass(className);

        // 调用方法
        return invoker.invokeInstanceMethod(instance, methodName, params);
    }

    /**
     * 生成子类并执行方法
     */
    public Object executeSubclass(String className, String superClassName,
                                  Map<String, Object> methodImplementations,
                                  String methodName, ArrayList<Object> params) throws Exception {
        // 生成子类
        Class<?> subclass = compiler.generateSubclass(className, superClassName, methodImplementations);
        log.info("子类生成成功: {} -> {}", className, superClassName);

        // 实例化类
        Object instance = invoker.instantiateClass(className);

        // 调用方法
        return invoker.invokeInstanceMethod(instance, methodName, params);
    }

    /**
     * 直接调用静态方法
     */
    public Object executeStaticMethod(String className, String methodName, ArrayList<Object> params) throws Exception {
        return invoker.invokeStaticMethod(className, methodName, params);
    }

    /**
     * 编译源代码并返回Class对象（不执行）
     */
    public Class<?> compileClass(String className, String sourceCode) throws Exception {
        return compiler.compileSource(className, sourceCode);
    }

    /**
     * 生成接口实现类并返回Class对象（不执行）
     */
    public Class<?> generateInterfaceClass(String className, String interfaceName,
                                           Map<String, Object> methodImplementations) throws Exception {
        return compiler.generateInterfaceImplementation(className, interfaceName, methodImplementations);
    }

    /**
     * 获取依赖管理器
     */
    public CodeBasedDependencyManager getDependencyManager() {
        return dependencyManager;
    }

    /**
     * 获取方法调用器
     */
    public DynamicMethodInvoker getMethodInvoker() {
        return invoker;
    }

    /**
     * 获取代码编译器
     */
    public DynamicJavaCompiler getCodeCompiler() {
        return compiler;
    }


    /**
     * 使用字符串方法实现生成接口实现并执行方法
     */
    public Object executeInterfaceImplementationWithStrings(String className, String interfaceName,
                                                            Map<String, String> methodImplementations,
                                                            String methodName, ArrayList<Object> params) throws Exception {
        // 生成接口实现类
        Class<?> implClass = compiler.generateInterfaceImplementationWithStrings(
                className, interfaceName, methodImplementations);
        log.info("接口实现类生成成功: {} -> {}", className, interfaceName);

        // 实例化类
        Object instance = invoker.instantiateClass(className);

        // 调用方法
        return invoker.invokeInstanceMethod(instance, methodName, params);
    }

    /**
     * 使用字符串方法实现生成子类并执行方法
     */
    public Object executeSubclassWithStrings(String className, String superClassName,
                                             Map<String, String> methodImplementations,
                                             String methodName, ArrayList<Object> params) throws Exception {
        // 生成子类
        Class<?> subclass = compiler.generateSubclassWithStrings(
                className, superClassName, methodImplementations);
        log.info("子类生成成功: {} -> {}", className, superClassName);

        // 实例化类
        Object instance = invoker.instantiateClass(className);

        // 调用方法
        return invoker.invokeInstanceMethod(instance, methodName, params);
    }

    /**
     * 安全调用静态方法（使用兼容性工具）
     */
    public Object executeStaticMethodSafely(String className, String methodName, ArrayList<Object> params) throws Exception {
        Class<?> clazz = compatibilityHelper.loadClassSafely(className);
        Method[] methods = clazz.getMethods();

        for (Method method : methods) {
            if (method.getName().equals(methodName) && method.getParameterCount() == params.size()) {
                // 检查参数兼容性
                boolean compatible = true;
                Class<?>[] paramTypes = method.getParameterTypes();

                for (int i = 0; i < paramTypes.length; i++) {
                    Object param = params.get(i);
                    if (param != null && !compatibilityHelper.isParameterCompatible(paramTypes[i], param.getClass())) {
                        compatible = false;
                        break;
                    }
                }

                if (compatible) {
                    return method.invoke(null, params.toArray());
                }
            }
        }

        throw new NoSuchMethodException("未找到兼容的静态方法: " + methodName + " in " + className);
    }


    // 在 DynamicCodeExecutor.java 中添加

    /**
     * 执行接口实现（强制重新生成类，避免缓存问题）
     */
    public Object executeInterfaceImplementationForce(String className, String interfaceName,
                                                      Map<String, String> methodImplementations,
                                                      String methodName, ArrayList<Object> params) throws Exception {
        // 生成接口实现类（强制重新生成）
        Class<?> implClass = compiler.generateClassForce(className, interfaceName, methodImplementations);
        log.info("接口实现类生成成功: {} -> {}", className, interfaceName);

        // 实例化类
        Object instance = invoker.instantiateClass(className);

        // 调用方法
        return invoker.invokeInstanceMethod(instance, methodName, params);
    }

    /**
     * 清除编译器缓存
     */
    public void clearCompilerCache() {
        compiler.clearClassCache();
        log.info("已清除编译器缓存");
    }

    /**
     * 清除特定目标类的编译器缓存
     */
    public void clearCompilerCacheForTarget(String targetName) {
        compiler.clearCacheForTarget(targetName);
    }

}